from PyQt4 import QtCore, QtGui
import sys

import datetime
import numpy

import UI
from UI.AddPersonToEventDiag import Ui_AddPersonToEventDiag
from UI.AddPersonToSubGroupDiag import Ui_AddPersonToSubGroupDiag
from UI.AddSubGroupExpenseDiag import Ui_AddSubGroupExpenseDiag
from UI.ChangePassword import Ui_ChangePassword
from UI.ConfirmDiag import Ui_ConfirmDiag
from UI.CreateNewEventDiag import Ui_CreateNewEventDiag
from UI.DependantsDiag import Ui_DependantsDiag
from UI.EditPeopleDiag import Ui_EditPeopleDiag
from UI.EditTripExpenseDiag import Ui_EditTripExpenseDiag
from UI.EmailPeopleOnEventDiag import Ui_EmailPeopleOnEventDiag
from UI.EventDatesSelectDiag import Ui_EventDatesSelectDiag
from UI.MainGui import Ui_MainWindow
from UI.PaymentDiag import Ui_PaymentDiag
from UI.PaymentMatrix import Ui_PaymentMatrix
from UI.SelectDependant import Ui_SelectDependant
from UI.SelectEventDiag import Ui_SelectEventDiag
from UI.SelectEventDiagAdmin import Ui_SelectEventDiagAdmin
from UI.SignInDiag import Ui_SignInDiag
from UI.UserDetailsDiag import Ui_UserDetailsDiag
from UI.ViewExpenseSummaryDiag import Ui_ViewExpenseSummaryDiag
from UI.ViewPaymentsDiag import Ui_ViewPaymentsDiag
from UI.ViewSpendingSummaryDiag import Ui_ViewSpendingSummaryDiag
from UI.ViewSubGroupExpenseDiag import Ui_ViewSubGroupExpenseDiag
from UI.ViewTripExpenseDiag import Ui_ViewTripExpenseDiag


import Email
from Email import EmailEvent
from Email import PaymentMatrixEmail
import Database.Database as Database

global PID
global Admin
global EventId
global DefaultDate
DefaultDate = QtCore.QDate.currentDate()

class EmailPeopleOnEvent(QtGui.QDialog, Ui_EmailPeopleOnEventDiag):
    def __init__(self, Database):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.Database = Database
        People = self.Database.GetPeopleOnEvent(EventId)
        self.PopulateRecipTable(People)
        self.connect(self.pushButton_2, QtCore.SIGNAL("clicked()"), self.SendMessages)
            
    def PopulateRecipTable(self, People):
        Row = 0
        for Person in People:
            self.tableWidget.insertRow(Row)
            Name = QtGui.QTableWidgetItem("""%s %s"""%(Person.f_Name, Person.l_Name))
            self.tableWidget.setItem(Row, 0, Name)
            Email = QtGui.QTableWidgetItem("""%s"""%(Person.Email))
            self.tableWidget.setItem(Row, 1, Email)
            
            
            self.tableWidget.setCellWidget(Row, 2, QtGui.QCheckBox())
            self.tableWidget.cellWidget(Row, 2).setTristate(False)
            self.tableWidget.cellWidget(Row, 2).setCheckState(2)
            
            Row += 1
        
        i = 0
        while (i < self.tableWidget.columnCount()):
            self.tableWidget.resizeColumnToContents(i)
            i = i + 1

    def SendMessages(self):
        row = 0
        People = {}
        while (row < self.tableWidget.rowCount()):
            Name = str(self.tableWidget.item(row, 0).text())
            Email = str(self.tableWidget.item(row, 1).text())
            
            if self.tableWidget.cellWidget(row, 2).checkState() == 2:
                People[Name] = Email
            row += 1
        EventName = self.Database.Events.GetEvent(EID = EventId)[0].EventName
        EmailEvent.EmailEvent(People, EventName, str(self.textEdit.toPlainText()))
        
class EmailFromPaymentMatrix(QtGui.QDialog, Ui_EmailPeopleOnEventDiag):
    def __init__(self, Database, Payments):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.Database = Database
        self.Payments = Payments
        People = self.Database.GetPeopleOnEvent(EventId)
        self.PopulateRecipTable(People)
        self.connect(self.pushButton_2, QtCore.SIGNAL("clicked()"), self.SendMessages)
            
    def PopulateRecipTable(self, People):
        Row = 0
        for Person in People:
            self.tableWidget.insertRow(Row)
            Name = QtGui.QTableWidgetItem("""%s %s"""%(Person.f_Name, Person.l_Name))
            self.tableWidget.setItem(Row, 0, Name)
            
            Email = QtGui.QTableWidgetItem("""%s"""%(Person.Email))
            self.tableWidget.setItem(Row, 1, Email)
            
            
            self.tableWidget.setCellWidget(Row, 2, QtGui.QCheckBox())
            self.tableWidget.cellWidget(Row, 2).setTristate(False)
            self.tableWidget.cellWidget(Row, 2).setCheckState(2)
            
            Row += 1
        
        i = 0
        while (i < self.tableWidget.columnCount()):
            self.tableWidget.resizeColumnToContents(i)
            i = i + 1

    def SendMessages(self):
        row = 0
        #People = self.Database.People.GetAllPeopleDict()  
        People = {}
        while (row < self.tableWidget.rowCount()):
            Name = str(self.tableWidget.item(row, 0).text())
            Email = str(self.tableWidget.item(row, 1).text())
            
            if self.tableWidget.cellWidget(row, 2).checkState() == 2:
                People[Name] = Email
            row += 1
        EventName = self.Database.Events.GetEvent(EID = EventId)[0].EventName
        PaymentMatrixEmail.EmailMatrix(People, self.Payments, None, str(self.textEdit.toPlainText()), EventName)
        
class PaymentMatrixDiag(QtGui.QDialog, Ui_PaymentMatrix):
    def __init__(self, Database):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.RowMapping = {}
        self.MapRowing = {}
        self.Database = Database
        
        
        #self.PopulateTables()
        
        self.ProgressDiag = QtGui.QProgressDialog(self)
        self.ProgressDiag.setLabelText("Generating Payment Matrix")
        self.ProgressDiag.setMaximum(0)
        self.ProgressDiag.setMinimum(0)
        self.ProgressDiag.show()
        
        
        self.GetDataThread = GetMainDataThread(self.Database, self.Database.GeneratePaymentMatrix, args = (EventId))
        self.connect(self.GetDataThread, QtCore.SIGNAL("update(PyQt_PyObject)"), self.GotData)
        self.GetDataThread.start()
        
        self.connect(self.tableWidget_2, QtCore.SIGNAL("cellChanged(int, int)"), self.CalculateTable)
        self.connect(self.EmailButton, QtCore.SIGNAL("clicked()"), self.EmailPeople)
        
    def EmailPeople(self):
        Payments = self.GetPayments()
        self.EmailDiag = EmailFromPaymentMatrix(self.Database, Payments)
        self.EmailDiag.show()
        
    def PopulateTables(self):
        self.People = self.Database.People.GetAllPeopleDict()          
        PIDs = self.Database.Events.GetPIDSOnEvent(EventId)
        Row = 0
        for PID in PIDs:
            Item = QtGui.QTableWidgetItem("""%s %s"""%(self.People[PID].f_Name, self.People[PID].l_Name))
            Item2 = QtGui.QTableWidgetItem(" ")
            Item2.setBackgroundColor(QtGui.QColor(0,0,0))
            self.tableWidget_2.insertRow(Row)
            self.tableWidget_2.insertColumn(Row)
            self.tableWidget_2.setItem(Row, Row, Item2)
            self.tableWidget_2.setHorizontalHeaderItem (Row, Item)
            self.tableWidget_2.setVerticalHeaderItem(Row, Item)
            
            self.tableWidget.insertRow(Row)
            self.tableWidget.setVerticalHeaderItem(Row, Item)
            
            self.RowMapping[PID] = Row
            self.MapRowing[Row] = PID
            Row += 1

        
        i = 0
        while (i < self.tableWidget_2.columnCount()):
            self.tableWidget_2.resizeColumnToContents(i)
            i = i + 1
        
        #self.Database.GeneratePaymentMatrix(EventId)
    def GotData(self, Data):
        self.ProgressDiag.reject()
        self.PopulateTables()
        Payments = Data[0]
        Data = Data[1]
        
        for Payment in Payments:
            Row = self.RowMapping[Payment[0]]
            Col = self.RowMapping[Payment[1]]
            Amount = Payment[2]
            Item = QtGui.QTableWidgetItem("""$ %.2f"""%(Amount))
            self.tableWidget_2.setItem(Row, Col, Item)
        
        for PID in Data.keys():
            print PID
            Row = self.RowMapping[PID]
            Col = 0
            AmountOwing = Data[PID][0] 
            Item = QtGui.QTableWidgetItem("""$ %.2f"""%(AmountOwing))
            self.tableWidget.setItem(Row, Col, Item)
        
            
        print "Done"
        
    def GetPayments(self):
        Payments = []
        row = 0
        cols = 0
        People = self.Database.People.GetAllPeopleDict() 
        while (row < self.tableWidget_2.rowCount()):
            col = 0
            while (col < self.tableWidget_2.columnCount()):
                Item = self.tableWidget_2.item(row, col)
                if Item != None:
                    Item = Item.text().replace("$","")
                    if Item != "":
                        #add Payment to both receiver and Payer
                        try:
                            if Item != 0.00:
                                if float(Item) > 0:
                                    Payer = """%s %s"""%(self.People[self.MapRowing[col]].f_Name, self.People[self.MapRowing[col]].l_Name)
                                    Rec = """%s %s"""%(self.People[self.MapRowing[row]].f_Name, self.People[self.MapRowing[row]].l_Name)
                                    Payments.append([Item, Payer, Rec])
                        except:
                            pass
                col +=1
            row += 1
        return Payments
        
        
    def CalculateTable(self):
        row = 0
        col = 0
        Nets = numpy.zeros(self.tableWidget_2.rowCount())
        while (row < self.tableWidget_2.rowCount()):
            Item = self.tableWidget.item(row, 0)
            print """Row %d"""%row
            if Item != None:
                TotalOwed = float(Item.text().replace("$",""))
                print """TotalOwed : %.2f"""%TotalOwed
                Nets[row] += TotalOwed
                col = 0
                while (col < self.tableWidget_2.columnCount()):
                    Item = self.tableWidget_2.item(row, col)
                    if Item != None:
                        Item = Item.text().replace("$","")
                        if Item != "":
                            #add Payment to both receiver and Payer
                            print Item
                            try:
                                Nets[row] -= float(Item)
                                Nets[col] += float(Item)
                            except ValueError:
                                pass
                    col +=1
            row += 1
        row = 0
        while (row < self.tableWidget_2.rowCount()):
            Net = Nets[row]
            Item = QtGui.QTableWidgetItem("""$ %.2f"""%(Net))
            self.tableWidget.setItem(row, 1, Item)
            row += 1
            
            
class SelectDependants(QtGui.QDialog, Ui_SelectDependant):
    def __init__(self, Database, All= False):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.All = All
        self.Database = Database
        self.PopulateList()
        
    def PopulateList(self):
        People = self.Database.People.GetAllPeopleDict()
        if self.All:
            Deps = self.Database.Events.GetPIDSOnEvent(EventId)
        else:
            Deps = self.Database.People.GetAllPersonsDeps(PID)
        
        
        
        Item = QtGui.QListWidgetItem()
        if not self.All:
            Item.setData(32,PID)
            Item.setText("%s %s"%(People[PID].f_Name, People[PID].l_Name))
            self.listWidget.addItem(Item)
        
        for Dep in Deps:
            Item = QtGui.QListWidgetItem()
            Item.setData(32,Dep)
            Item.setText("%s %s"%(People[Dep].f_Name, People[Dep].l_Name))
            self.listWidget.addItem(Item)
    
    def GetSelectedPID(self):
        Item = self.listWidget.item(self.listWidget.currentRow())
        ID = Item.data(32).toInt()[0]
        return ID

class Dedendants(QtGui.QDialog, Ui_DependantsDiag):
    def __init__(self, Database):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.Database = Database
        self.PopulateWindow()
        self.connect(self.listWidget, QtCore.SIGNAL("itemSelectionChanged()"), self.PopulateDependants)
        self.connect(self.radioButton, QtCore.SIGNAL("toggled(bool)"), self.PopulateWindow)
        self.connect(self.AddDepBut, QtCore.SIGNAL("clicked()"), self.AddDependancy)
        
    def AddDependancy(self):
        Item = self.listWidget.item(self.listWidget.currentRow())
        ID = Item.data(32).toInt()[0]
        Deps = self.Database.People.GetAllPersonsDeps(ID)
        AllPeople = self.Database.People.GetAllPeopleDict()
        People = []
        for PID in AllPeople.keys():
            if PID != ID:
                if PID not in Deps:
                    People.append(AllPeople[PID])
        self.AddPersonDiag = AddPersonToSubGroup(People)
        self.AddPersonDiag.show()
        self.connect(self.AddPersonDiag, QtCore.SIGNAL("accepted()"), self.AddDepAccepted)
        
    def AddDepAccepted(self):
        Item = self.listWidget.item(self.listWidget.currentRow())
        ID = Item.data(32).toInt()[0]
        PIDs = self.AddPersonDiag.GetAddedPeople()
        for PID in PIDs:
            self.Database.People.AddDependancy(ID, PID)
        self.PopulateDependants()
        
        
    def PopulateDependants(self):      
        Item = self.listWidget.item(self.listWidget.currentRow())
        ID = Item.data(32).toInt()[0]
        AllPeople = self.Database.People.GetAllPeopleDict()
        ##Get Dependancies
        Deps = self.Database.People.GetAllPersonsDeps(ID)
        while(self.tableWidget.rowCount() > 0):
            self.tableWidget.removeRow(0)
        for Dep in Deps:
            self.tableWidget.insertRow(self.tableWidget.rowCount())
            #self.tableWidget.setItem(self.tableWidget.rowCount()-1, 0, QtGui.QTableWidgetItem("""%d"""%Expense.SgExp_id))
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 0, QtGui.QTableWidgetItem("""%s %s"""%(AllPeople[Dep].f_Name, AllPeople[Dep].l_Name)))
            
            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 1, QtGui.QPushButton("Delete"))
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 1).uniqueId = """%d"""%Dep
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 1).clicked.connect(self.OnDeleteEvent)
        
    def OnDeleteEvent(self): 
        Dep =  int(self.sender().uniqueId)
        Item = self.listWidget.item(self.listWidget.currentRow())
        ID = Item.data(32).toInt()[0]
        self.Database.People.RemoveDependacy(ID, Dep)
        self.PopulateDependants()
        
    def PopulateWindow(self):
        People = self.Database.People.GetAllPeopleDict()
        self.listWidget.clear()
        if self.radioButton.isChecked():
            Ids = self.Database.Events.GetPIDSOnEvent(EventId)
        else:
            Ids = People.keys()
            
        for Id in Ids:
            Item = QtGui.QListWidgetItem()
            Item.setData(32,Id)
            Item.setText("%s %s"%(People[Id].f_Name, People[Id].l_Name))
            self.listWidget.addItem(Item)
    
class ViewPayments(QtGui.QDialog, Ui_ViewPaymentsDiag):
    def __init__(self, Database):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.Database = Database
        self.CurrentPID = PID
        self.PopulateComboBox()
        self.PopulatePaymentsMade()
        self.PopulatePaymentsRecieved()
        self.connect(self.AddNewExpenseBut, QtCore.SIGNAL("clicked()"), self.AddNewPayment)
        
    def AddNewPayment(self):
        self.AddDiag = MakePayment(self.Database)
        self.AddDiag.show()
        self.connect(self.AddDiag, QtCore.SIGNAL("accepted()"), self.EditingAccepted)
        
    def PopulateComboBox(self):
        self.comboBox.clear()
        People = self.Database.GetPeopleOnEvent(EventId)
        index = 0
        for Person in People:
            if Person.PID == self.CurrentPID:
                index = self.comboBox.count()
            self.comboBox.addItem("""%s %s"""%(Person.f_Name, Person.l_Name))
            self.comboBox.setItemData(self.comboBox.count()-1, Person.PID)
        self.comboBox.setCurrentIndex(index)
        self.connect(self.comboBox, QtCore.SIGNAL("currentIndexChanged(int)"), self.ComboChange)
    
    def ComboChange(self):
        self.CurrentPID = self.comboBox.itemData(self.comboBox.currentIndex()).toInt()[0]
        self.PopulatePaymentsMade()
        self.PopulatePaymentsRecieved()
        
    def PopulatePaymentsMade(self):
        Payments = self.Database.Payments.GetPayments(PID = self.CurrentPID, EID = EventId)
        People = self.Database.People.GetAllPeopleDict()
        Ids = Payments.keys()
        while(self.tableWidget.rowCount() > 0):
            self.tableWidget.removeRow(0)
        for Id in Ids:
            Payment = Payments[Id]
            self.tableWidget.insertRow(self.tableWidget.rowCount())
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 0, QtGui.QTableWidgetItem("""%s %s"""%(People[Payment.RID].f_Name, People[Payment.RID].l_Name)))
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 1, QtGui.QTableWidgetItem("""$%0.2f"""%(Payment.Amount)))
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 2, QtGui.QTableWidgetItem("""%s"""%(Payment.Desc)))
            
            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 3, QtGui.QPushButton("Edit"))
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 3).uniqueId = """%d"""%Payment.Pay_ID
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 3).clicked.connect(self.OnEditPayment)
            
            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 4, QtGui.QPushButton("Delete"))
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 4).uniqueId = """%d"""%Payment.Pay_ID
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 4).clicked.connect(self.OnDeletePayment)
        i = 0
        while (i < self.tableWidget.columnCount()):
            self.tableWidget.resizeColumnToContents(i)
            i = i + 1
            
    def PopulatePaymentsRecieved(self):
        Payments = self.Database.Payments.GetPayments(RID = self.CurrentPID, EID = EventId)
        People = self.Database.People.GetAllPeopleDict()
        Ids = Payments.keys()
        while(self.tableWidget_2.rowCount() > 0):
            self.tableWidget_2.removeRow(0)
        for Id in Ids:
            Payment = Payments[Id]
            self.tableWidget_2.insertRow(self.tableWidget_2.rowCount())
            self.tableWidget_2.setItem(self.tableWidget_2.rowCount()-1, 0, QtGui.QTableWidgetItem("""%s %s"""%(People[Payment.PID].f_Name, People[Payment.PID].l_Name)))
            self.tableWidget_2.setItem(self.tableWidget_2.rowCount()-1, 1, QtGui.QTableWidgetItem("""$%0.2f"""%(Payment.Amount)))
            self.tableWidget_2.setItem(self.tableWidget_2.rowCount()-1, 2, QtGui.QTableWidgetItem("""%s"""%(Payment.Desc)))
            
            self.tableWidget_2.setCellWidget(self.tableWidget_2.rowCount()-1, 3, QtGui.QPushButton("Edit"))
            self.tableWidget_2.cellWidget(self.tableWidget_2.rowCount()-1, 3).uniqueId = """%d"""%Payment.Pay_ID
            self.tableWidget_2.cellWidget(self.tableWidget_2.rowCount()-1, 3).clicked.connect(self.OnEditPayment)
            
            self.tableWidget_2.setCellWidget(self.tableWidget_2.rowCount()-1, 4, QtGui.QPushButton("Delete"))
            self.tableWidget_2.cellWidget(self.tableWidget_2.rowCount()-1, 4).uniqueId = """%d"""%Payment.Pay_ID
            self.tableWidget_2.cellWidget(self.tableWidget_2.rowCount()-1, 4).clicked.connect(self.OnDeletePayment)
        i = 0
        while (i < self.tableWidget.columnCount()):
            self.tableWidget.resizeColumnToContents(i)
            i = i + 1
    
    def OnEditPayment(self):
        Pay_Id = int(self.sender().uniqueId)
        self.EditDiag = MakePayment(self.Database, Pay_Id)
        self.EditDiag.show()
        self.connect(self.EditDiag, QtCore.SIGNAL("accepted()"), self.EditingAccepted)
        
    def EditingAccepted(self):
        self.PopulatePaymentsMade()
        self.PopulatePaymentsRecieved()
        
    def OnDeletePayment(self):
        Pay_id =  int(self.sender().uniqueId)
        self.ConfirmDelete = ConfirmDiag("Are you sure you want to delete?")
        self.ConfirmDelete.ID = str(Pay_id)
        self.connect(self.ConfirmDelete, QtCore.SIGNAL("accepted()"), self.DeleteAccepted)
        self.ConfirmDelete.show()
        
    def DeleteAccepted(self):
        Pay_id = int(self.ConfirmDelete.ID)
        self.Database.Payments.RemovePayment(Pay_id)
        self.PopulatePaymentsMade()
        self.PopulatePaymentsRecieved()
        
        
class MakePayment(QtGui.QDialog, Ui_PaymentDiag):
    def __init__(self, Database, PaymentID = -1):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.Database = Database
        self.currentPID = PID
        self.RXId = -1
        self.PaymentID = PaymentID
        self.PopulateWindow()
        self.connect(self.AmountEdit, QtCore.SIGNAL("editingFinished()"), self.CheckAmount)
        self.connect(self.ChangePIDBut, QtCore.SIGNAL("clicked()"), self.ChangePID)
        self.connect(self.ChangeRIDBut, QtCore.SIGNAL("clicked()"), self.ChangeRID)
        self.connect(self.FinishedBut, QtCore.SIGNAL("clicked()"), self.Finished)
        self.connect(self.CancelBut, QtCore.SIGNAL("clicked()"), self.reject)
        
    def PopulateWindow(self):
        if self.PaymentID != -1:
            self.Payment = self.Database.Payments.GetPayments(Pay_Id = self.PaymentID)[self.PaymentID]
            self.currentPID = self.Payment.PID
            People = self.Database.People.GetAllPeopleDict()
            self.PayingPersonEdit.setText("""%s %s"""%(People[self.currentPID].f_Name, People[self.currentPID].l_Name))
            self.RXId = self.Payment.RID
            self.ReceivingPID.setText("""%s %s"""%(People[self.Payment.RID].f_Name, People[self.Payment.RID].l_Name))
            date = QtCore.QDate(self.Payment.Date.year, self.Payment.Date.month, self.Payment.Date.day)
            self.dateEdit.setDate(date)
            self.textEdit.setText(self.Payment.Desc)
            self.AmountEdit.setText("""$ %.2f"""%self.Payment.Amount)  
            
            
        else:
            Person = self.Database.People.GetPerson(PID = self.currentPID)[0]
            self.PayingPersonEdit.setText("""%s %s"""%(Person.f_Name, Person.l_Name))
            self.AmountEdit.setText("""$0.0""")       
            self.dateEdit.setDate(DefaultDate)
        

    def ChangePID(self):
        self.SelectDepDiag = SelectDependants(self.Database)
        self.SelectDepDiag.show()
        self.connect(self.SelectDepDiag, QtCore.SIGNAL("accepted()"), self.ChangePersonAccept)
        
    def ChangePersonAccept(self):
        self.currentPID = self.SelectDepDiag.GetSelectedPID()
        Person = self.Database.People.GetPerson(PID = self.currentPID)[0]
        self.PayingPersonEdit.setText("""%s %s"""%(Person.f_Name, Person.l_Name))
    
    def ChangeRID(self):
        self.SelectRecDiag = SelectDependants(self.Database, True)
        self.SelectRecDiag.show()
        self.connect(self.SelectRecDiag, QtCore.SIGNAL("accepted()"), self.ChangeRecAccept)
        
    def ChangeRecAccept(self):
        self.RXId = self.SelectRecDiag.GetSelectedPID()
        Person = self.Database.People.GetPerson(PID = self.RXId)[0]
        self.ReceivingPID.setText("""%s %s"""%(Person.f_Name, Person.l_Name))
    
    def CheckAmount(self):
        Number, FloatCheck = self.AmountEdit.text().replace('$','').toFloat()
        if not FloatCheck:
            self.AmountEdit.setText(self.Amount)
            self.Message = QtGui.QMessageBox(self)
            self.Message.setText("Input must be of type float")
            self.Message.show()
        else:
            if '$' not in self.AmountEdit.text():
                text = '$' + self.AmountEdit.text()
                self.AmountEdit.setText(text)
                self.Amount = text
                
    def Finished(self):
        if self.RXId == -1:
            self.Message = QtGui.QMessageBox(self)
            self.Message.setText("You have not selected who is recieving the payment")
            self.Message.show()
        else:
            if self.PaymentID != -1:
                self.Payment.Amount, FloatCheck = self.AmountEdit.text().replace('$','').toFloat()
                self.Payment.Desc = self.textEdit.toPlainText()
                self.Payment.Date = datetime.date(self.dateEdit.date().year(),
                                    self.dateEdit.date().month(),
                                    self.dateEdit.date().day())
                self.Payment.RID = self.RXId
                self.Payment.PID = self.currentPID
                
                self.Database.Payments.UpdatePayment(self.Payment)
                
            else:
                Date = datetime.date(self.dateEdit.date().year(),
                            self.dateEdit.date().month(),
                            self.dateEdit.date().day())
                Amount, FloatCheck = self.AmountEdit.text().replace('$','').toFloat()
                Desc = self.textEdit.toPlainText()
                self.Database.Payments.AddPayment(EventId, self.currentPID, self.RXId,
                                                  Amount,
                                                  Date, Desc)
            
            self.accept()
                
        
        
class ChangePassword(QtGui.QDialog, Ui_ChangePassword):
    def __init__(self, Database, ID):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.ID = ID
        self.connect(self.pushButton, QtCore.SIGNAL("clicked()"), self.Done)
        self.Database = Database
    
    def Done(self):
        Person = self.Database.People.GetPerson(PID = self.ID)[0]
        Person.SetPassWord(self.lineEdit.text())
        self.Database.People.UpdatePerson(Person)
        self.accept()

class ModifyDetails(QtGui.QDialog, Ui_UserDetailsDiag):
    def __init__(self, Database, OtherPID = -1):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.Database = Database
        
        if OtherPID == -1:
            self.CurrentPID = PID
        elif OtherPID == -2:
            self.CurrentPID = -2
        else:
            self.CurrentPID = OtherPID
        
        if self.CurrentPID != -2:
            print PID
            print self.CurrentPID
            Person = self.Database.People.GetPerson(PID = self.CurrentPID)[0]
            
            self.LineEditId.setText(str(Person.PID))
            self.LineEditFirstName.setText(Person.f_Name)
            self.LineEditSecondName.setText(Person.l_Name)
            self.LineEditUserName.setText(Person.UserName)
            self.EmailAddressEdit.setText(Person.Email)
            self.connect(self.DoneButton, QtCore.SIGNAL("clicked()"), self.Done)
            self.connect(self.pushButton_2, QtCore.SIGNAL("clicked()"), self.ChangePassword)
        else:
            self.connect(self.DoneButton, QtCore.SIGNAL("clicked()"), self.CreateNewPerson)
    
    def ChangePassword(self):
        self.ChangePwDiag = ChangePassword(self.Database, self.CurrentPID)
        self.ChangePwDiag.show()
    
    def Done(self):
        Person = self.Database.People.GetPerson(PID = self.CurrentPID)[0]
        Person.f_Name = self.LineEditFirstName.text()
        Person.l_Name = self.LineEditSecondName.text()
        Person.UserName = self.LineEditUserName.text()
        Person.Email = self.EmailAddressEdit.text()
        self.Database.People.UpdatePerson(Person)
        self.accept()
    
    def CreateNewPerson(self):
        f_Name = self.LineEditFirstName.text()
        l_Name = self.LineEditSecondName.text()
        UserName = self.LineEditUserName.text()
        Email = self.EmailAddressEdit.text()
        self.Database.People.AddPerson(f_Name, l_Name, UserName, Password = 'grogan', Email = Email)
        self.accept()
        
class DatesOnEventDiag(QtGui.QDialog, Ui_EventDatesSelectDiag):
    def __init__(self, Database):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.Database = Database
        self.CurrentPID = PID
        
        self.tableWidget.resizeColumnToContents(2)
        self.connect(self.DoneButton, QtCore.SIGNAL("clicked()"), self.OnDone)
        
        self.PopulateWindow()
        
        
    def PopulateWindow(self):
        global EventId
        Delta = 0
        Event = self.Database.Events.GetEvent(EID = EventId)[0]
        StartDate = Event.StartDate
        EndDate = Event.EndDate
        PersonDates = self.Database.Events.GetDatesPersonOnEvent(EventId, self.CurrentPID)
        while (StartDate + datetime.timedelta(Delta)) != EndDate + datetime.timedelta(1):
            Date = (StartDate + datetime.timedelta(Delta))
            self.tableWidget.insertRow(self.tableWidget.rowCount())
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 0, QtGui.QTableWidgetItem("""%d/%d/%d"""%(Date.day, Date.month, Date.year)))
            
            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 1, QtGui.QCheckBox())
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 1).setTristate(False)
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 1).setCheckState(2)
            self.connect(self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 1), QtCore.SIGNAL("clicked()"),self.CheckAction)
            
            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 2, QtGui.QSpinBox())
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 2).setRange(0,100)
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 2).setSingleStep(25)
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 2).setValue(100)
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 2).setEnabled(True)
            
            ##check on the users values.
            i = 0
            while i < len(PersonDates):
                if Date == PersonDates[i][0]:
                    self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 2).setValue(PersonDates[i][1])
                    if PersonDates[i][1] == 0:
                        self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 1).setCheckState(0)
                        self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 2).setEnabled(False)
                    else:
                        self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 1).setCheckState(2)
                        self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 2).setEnabled(True)
                i = i + 1
            Delta = Delta + 1
        
    
    def GetDatesPresentFromWindow(self):
        i = 0
        PersonDates = []
        while i < self.tableWidget.rowCount():
            Date = self.tableWidget.item(i,0).text().split("""/""")
            Present = self.tableWidget.cellWidget(i, 2).value()
            PersonDates.append((datetime.date(int(Date[2]), int(Date[1]), int(Date[0])),Present))    
            i = i + 1
        return PersonDates
    
    def OnDone(self):
        global EventId
        self.Database.Events.UpdateEventPeople(EventId,
                                              self.CurrentPID,
                                              self.GetDatesPresentFromWindow())
        self.accept()
        
    def CheckAction(self):
        i = 0
        PersonDates = []
        while i < self.tableWidget.rowCount():
            if self.tableWidget.cellWidget(i, 1).checkState() == 2:
                self.tableWidget.cellWidget(i, 2).setEnabled(True)
                self.tableWidget.cellWidget(i, 2).setValue(100)
            else:
                self.tableWidget.cellWidget(i, 2).setEnabled(False)
                self.tableWidget.cellWidget(i, 2).setValue(0)
            i = i + 1

class EditPeople(QtGui.QDialog, Ui_EditPeopleDiag):
    def __init__(self, Database):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.Database = Database
        self.connect(self.NewPersonButton, QtCore.SIGNAL("clicked()"), self.CreateNewPerson)
        self.PopulateTable()
    
    def PopulateTable(self):
        People = self.Database.People.GetAllPeopleDict()
        while(self.tableWidget.rowCount() > 0):
            self.tableWidget.removeRow(0)
        for PID in People.keys():
            Person = People[PID]
            self.tableWidget.insertRow(self.tableWidget.rowCount())
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 0, QtGui.QTableWidgetItem("""%s %s"""%(Person.f_Name, Person.l_Name)))
            
            
            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 2, QtGui.QPushButton("Edit"))
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 2).uniqueId = """%d"""%Person.PID
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 2).clicked.connect(self.OnEditPerson)
            
    def OnEditPerson(self):
        PID = int(self.sender().uniqueId)
        self.EditDiag = ModifyDetails(self.Database, PID)
        self.EditDiag.show()
        self.connect(self.EditDiag, QtCore.SIGNAL("accepted()"), self.PopulateTable)
        
    def CreateNewPerson(self):
        self.EditDiag = ModifyDetails(self.Database, -2)
        self.EditDiag.show()
        self.connect(self.EditDiag, QtCore.SIGNAL("accepted()"), self.PopulateTable)
        
class ConfirmDiag(QtGui.QDialog, Ui_ConfirmDiag):
    def __init__(self, Message):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.label.setText(Message)
        self.ID = 0

class SignIn(QtGui.QDialog, Ui_SignInDiag):
    def __init__(self):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
      
class SelectEvent(QtGui.QDialog, Ui_SelectEventDiag):
    def __init__(self, Database):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        Events = Database.Events.GetEventsPersonOn(PID)
        for Event in Events:
            self.listWidget.addItem("""ID:%d  EventName:%s"""% (Event.EID, Event.EventName))
        self.listWidget.setCurrentRow(0)
    
    def GetEvent(self):
        return int(self.listWidget.currentItem().text().split(' ')[0].replace('ID:',''))
        
class SelectEventAdmin(QtGui.QDialog, Ui_SelectEventDiagAdmin):
    def __init__(self, Database):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.Database = Database
        self.PopulateList()
        self.connect(self.CreateNewEventButton, QtCore.SIGNAL("clicked()"), self.AddNewEvent)
    
    def PopulateList(self):
        self.listWidget.clear()
        Events = self.Database.Events.GetAllEvents()
        for Event in Events:
            self.listWidget.addItem("""ID:%d  EventName:%s"""% (Event.EID, Event.EventName))
        self.listWidget.setCurrentRow(0)
    
    def GetEvent(self):
        return int(self.listWidget.currentItem().text().split(' ')[0].replace('ID:',''))
    
    def AddNewEvent(self):
        self.createNewEventDiag = AdminCreateNewEvent(self.Database)
        self.createNewEventDiag.show()
        self.connect(self.createNewEventDiag, QtCore.SIGNAL("accepted()"), self.PopulateList)

class AdminCreateNewEvent(QtGui.QDialog, Ui_CreateNewEventDiag):
    def __init__(self, Database):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.Database = Database
        self.connect(self.OkButton, QtCore.SIGNAL("clicked()"), self.SaveEvent)
        
    def SaveEvent(self):
        EventName = self.EventNameEdit.text()
        EventDesc = self.EventDescEdit.text()
        StartDate = datetime.date(self.StartDateEdit.date().year(),
                                  self.StartDateEdit.date().month(),
                                  self.StartDateEdit.date().day())
        EndDate = datetime.date(self.EndDateEdit.date().year(),
                                self.EndDateEdit.date().month(),
                                self.EndDateEdit.date().day())
        self.Database.Events.AddEvent(EventName, StartDate, EndDate, EventDesc)
        self.accept()
        
class EditTripExpense(QtGui.QDialog, Ui_EditTripExpenseDiag):
    def __init__(self, DataBase, ExpenseId = -1):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.Result = 1
        self.ExpenseId = ExpenseId
        self.Expense = None
        self.Database = DataBase
        self.currentPID = PID
        self.PopulateWindow()
        
    
    def PopulateWindow(self):
        if self.ExpenseId != -1:
            self.Expense = self.Database.TripExpenses.GetExpenses(self.ExpenseId)[0]
            Person = self.Database.People.GetPerson(PID = self.Expense.PID)[0]
            self.currentPID = self.Expense.PID
            
            self.ExpenseOwner.setText("""%s %s"""%(Person.f_Name, Person.l_Name))
            Desc = self.Expense.Desc.split('\n\n')
            self.ExpenseName.setText(Desc[0])
            self.ExpenseDesc.setPlainText(Desc[-1])

            date = QtCore.QDate(self.Expense.Date.year, self.Expense.Date.month, self.Expense.Date.day)
            self.ExpenseDateEdit.setDate(date)
            self.ExpenseAmountEdit.setText("""$%0.2f"""%self.Expense.Amount)
            self.Amount = self.ExpenseAmountEdit.text()
        else:
            Person = self.Database.People.GetPerson(PID = PID)[0]
            self.ExpenseOwner.setText("""%s %s"""%(Person.f_Name, Person.l_Name))
            self.ExpenseAmountEdit.setText("""$%0.2f"""%0.0)
            self.ExpenseDateEdit.setDate(DefaultDate)
            self.Amount = self.ExpenseAmountEdit.text()
        
        self.connect(self.AddAnotherExpenseBut, QtCore.SIGNAL("clicked()"), self.CreateNewEvent)   
        self.connect(self.FinishedBut, QtCore.SIGNAL("clicked()"), self.Finished)
        self.connect(self.CancelBut, QtCore.SIGNAL("clicked()"), self.Cancel)
        self.connect(self.ChangePerson, QtCore.SIGNAL("clicked()"), self.ChangePersonAction)
        
        self.connect(self.ExpenseAmountEdit, QtCore.SIGNAL("editingFinished()"), self.CheckAmount)
    
    def ChangePersonAction(self):
        self.SelectDepDiag = SelectDependants(self.Database)
        self.SelectDepDiag.show()
        self.connect(self.SelectDepDiag, QtCore.SIGNAL("accepted()"), self.ChangePersonAccept)
        
    def ChangePersonAccept(self):
        self.currentPID = self.SelectDepDiag.GetSelectedPID()
        Person = self.Database.People.GetPerson(PID = self.currentPID)[0]
        self.ExpenseOwner.setText("""%s %s"""%(Person.f_Name, Person.l_Name))

    
    def CheckAmount(self):
        Number, FloatCheck = self.ExpenseAmountEdit.text().replace('$','').toFloat()
        if not FloatCheck:
            self.ExpenseAmountEdit.setText(self.Amount)
            self.Message = QtGui.QMessageBox(self)
            self.Message.setText("Input must be of type float")
            self.Message.show()
        else:
            if '$' not in self.ExpenseAmountEdit.text():
                text = '$' + self.ExpenseAmountEdit.text()
                self.ExpenseAmountEdit.setText(text)
                self.Amount = text

    def CheckExpenseTitle(self):
        Res = False
        if self.ExpenseName.text() != "":
            Res = True
        return Res
   
    def Finished(self):
        if self.CheckExpenseTitle():
            if self.Expense != None and self.ExpenseId != -1:
                self.Expense.PID = self.currentPID
                self.Expense.Desc = self.ExpenseName.text() + """\n\n""" + self.ExpenseDesc.toPlainText()
                self.Expense.Amount = float(self.ExpenseAmountEdit.text().replace('$',''))
                self.Expense.Date = datetime.date(self.ExpenseDateEdit.date().year(),
                                  self.ExpenseDateEdit.date().month(),
                                  self.ExpenseDateEdit.date().day())
                self.Database.TripExpenses.UpdateExpense(self.Expense)
            else:
                Date = datetime.date(self.ExpenseDateEdit.date().year(),
                                  self.ExpenseDateEdit.date().month(),
                                  self.ExpenseDateEdit.date().day())
                ExpenseDesc = self.ExpenseName.text() + """\n\n""" + self.ExpenseDesc.toPlainText()
                Amount = float(self.ExpenseAmountEdit.text().replace('$',''))
                
                self.Database.TripExpenses.AddExpense(EventId, self.currentPID, Date, ExpenseDesc, Amount, self.Database.Events.GetPIDSOnEvent(EventId))
                
            self.accept()
        else:
            self.Message = QtGui.QMessageBox(self)
            self.Message.setText("Please enter an expense name")
            self.Message.show()
    
    def CreateNewEvent(self):
        self.Result = 2
        self.Finished()
    
    def Cancel(self):
        self.reject()
        
class ViewTripExpense(QtGui.QDialog, Ui_ViewTripExpenseDiag):
    def __init__(self, Database):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.Database = Database
        self.connect(self.AddNewExpenseBut, QtCore.SIGNAL("clicked()"), self.CreateNewExpense)
        self.PopulateTable()
        
        
    def PopulateTable(self):
        
        while(self.tableWidget.rowCount() > 0):
            self.tableWidget.removeRow(0)
        Expenses = self.Database.TripExpenses.GetExpenses(EID = EventId)
        People = self.Database.People.GetAllPeopleDict()
        for Expense in Expenses:
            self.tableWidget.insertRow(self.tableWidget.rowCount())
            #self.tableWidget.setItem(self.tableWidget.rowCount()-1, 0, QtGui.QTableWidgetItem("""%d"""%Expense.TexID))
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 0, QtGui.QTableWidgetItem("""%d/%d/%d"""%(Expense.Date.day, Expense.Date.month, Expense.Date.year)))
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 1, QtGui.QTableWidgetItem("""%s"""%Expense.Desc.split("\n\n")[0]))
            
            Person = People[Expense.PID]
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 2, QtGui.QTableWidgetItem("""%s %s"""%(Person.f_Name, Person.l_Name)))

            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 3, QtGui.QTableWidgetItem("""%.2f"""%Expense.Amount))

            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 4, QtGui.QPushButton("Edit"))
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 4).uniqueId = """%d"""%Expense.TexID
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 4).clicked.connect(self.OnEditExpense)
            
            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 5, QtGui.QPushButton("Delete"))
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 5).uniqueId = """%d"""%Expense.TexID
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 5).clicked.connect(self.OnDeleteExpense)
      
    def OnEditExpense(self):
        ExpId =  int(self.sender().uniqueId)
        self.EditExpenseDiag = EditTripExpense(self.Database, ExpId)
        self.EditExpenseDiag.show()
        self.connect(self.EditExpenseDiag, QtCore.SIGNAL("accepted()"), self.OnAcceptEdit)
        self.connect(self.EditExpenseDiag, QtCore.SIGNAL("rejected()"), self.PopulateTable)
        
    def OnAcceptEdit(self):
        if self.EditExpenseDiag.Result == 2:
            self.CreateNewExpense()
        self.PopulateTable()
        
    def OnDeleteExpense(self):
        button =  self.sender()
        Expense = self.Database.TripExpenses.GetExpenses(TexId = int(button.uniqueId))[0]
        self.ConfirmDelete = ConfirmDiag("Are you sure you want to delete %s?"%Expense.Desc.split("\n\n")[0])
        self.ConfirmDelete.ID = button.uniqueId
        self.connect(self.ConfirmDelete, QtCore.SIGNAL("accepted()"), self.DeleteExpenseAccepted)
        self.ConfirmDelete.show()
        
    def DeleteExpenseAccepted(self):
        self.Database.TripExpenses.RemoveExpense(int(self.ConfirmDelete.ID))
        self.PopulateTable()
        
    def CreateNewExpense(self):
        self.EditExpenseDiag = EditTripExpense(self.Database)
        self.EditExpenseDiag.show()
        self.connect(self.EditExpenseDiag, QtCore.SIGNAL("accepted()"), self.OnAcceptEdit)
        self.connect(self.EditExpenseDiag, QtCore.SIGNAL("rejected()"), self.PopulateTable)

class AddSubGroupExpense(QtGui.QDialog, Ui_AddSubGroupExpenseDiag):
    def __init__(self, Database, SGExpId = -1):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        global EventId
        global PID
        
        self.Database = Database
        self.Amount = '$0.0'
        self.CurrentPID = PID

        self.SgExp_id = SGExpId
        if SGExpId != -1:    
            self.AddedPIDs=self.Database.SubGroupExpenses.GetAllPeopleInSubgroupOnEvent(SGExpId, EventId)
        else:
            self.AddedPIDs=[[PID, 0.0]]

        self.connect(self.DoneButton, QtCore.SIGNAL("clicked()"), self.Finished)
        self.connect(self.ExpenseAmount, QtCore.SIGNAL("editingFinished()"), self.CheckAmount)
        self.connect(self.AddPersonButton, QtCore.SIGNAL("clicked()"), self.AddPerson)
        self.connect(self.ChangePersonButton, QtCore.SIGNAL("clicked()"), self.ChangePerson)
        self.connect(self.EvenlyDistributeBut, QtCore.SIGNAL("clicked()"), self.EvenlyDitributeExpense)
        self.ExpenseAmount.setText(self.Amount)
        
        self.InitTable()
        self.PopulateTable()
        self.PopulatePersonData()

    def ChangePerson(self):
        self.SelectDepDiag = SelectDependants(self.Database)
        self.SelectDepDiag.show()
        self.connect(self.SelectDepDiag, QtCore.SIGNAL("accepted()"), self.ChangePersonAccept)
        
    def ChangePersonAccept(self):
        self.CurrentPID = self.SelectDepDiag.GetSelectedPID()
        self.PopulatePersonData()
        
    def PopulatePersonData(self):
        Person = self.Database.People.GetPerson(PID = self.CurrentPID)[0]
        self.PersonNameEdit.setText("""%s %s"""%(Person.f_Name, Person.l_Name))
          
    def CheckAmount(self):
        Number, FloatCheck = self.ExpenseAmount.text().replace('$','').toFloat()
        if not FloatCheck:
            self.ExpenseAmount.setText(self.Amount)
            self.Message = QtGui.QMessageBox(self)
            self.Message.setText("Input must be of type float")
            self.Message.show()
        else:
            if '$' not in self.ExpenseAmount.text():
                text = '$' + self.ExpenseAmount.text()
                self.ExpenseAmount.setText(text)
                self.Amount = text
        self.PopulateTable()
            
    def CheckExpenseTitle(self):
        Res = False
        if self.ExpenseTitle.text() != "":
            Res = True
        return Res
        
    def Finished(self):
        global EventId
        if self.CheckExpenseTitle():
            Diff = self.CheckProps()
            if abs(Diff) < 10:
                if self.SgExp_id == -1:
                    Date = datetime.date(self.ExpenseDate.date().year(),
                                        self.ExpenseDate.date().month(),
                                        self.ExpenseDate.date().day())
                    Amount = float(self.ExpenseAmount.text().replace('$',''))
                    Desc = self.ExpenseTitle.text() + """\n\n""" + self.ExpenseDesc.toPlainText()
                    self.Database.SubGroupExpenses.AddSubGroupExpense(EventId, self.CurrentPID, Desc, Amount, Date, self.AddedPIDs)
                else:
                    Expense =self.Database.SubGroupExpenses.GetSubGroupExpenses(SgExp_id = self.SgExp_id)[0]
                    Expense.PID = self.CurrentPID
                    Expense.Amount = float(self.ExpenseAmount.text().replace('$',''))
                    Expense.Desc = self.ExpenseTitle.text() + '\n\n' + self.ExpenseDesc.toPlainText()
                    Expense.Date = datetime.date(self.ExpenseDate.date().year(),
                                        self.ExpenseDate.date().month(),
                                        self.ExpenseDate.date().day())
                    self.Database.SubGroupExpenses.UpdateSubGroupExpense(Expense, self.AddedPIDs)
                self.accept()
            else:
                self.Message = QtGui.QMessageBox(self)
                self.Message.setText("""The amounts allocated to people do not add up to the total expense amount. The difference is $ %.2f"""%Diff/100.0)
                self.Message.show() 
        else:
            self.Message = QtGui.QMessageBox(self)
            self.Message.setText("Please enter an expense name")
            self.Message.show()
    
    def AddPerson(self):
        global EventId
        PeopleOnEvent = self.Database.GetPeopleOnEvent(EventId)
        PeopleToAdd = []
        PIDsInList = []
        
        for PID, Prop in self.AddedPIDs:
            PIDsInList.append(PID)
            
        for Person in PeopleOnEvent:
            if Person.PID in PIDsInList:
                pass
            else:
                PeopleToAdd.append(Person)
        self.AddPersonDiag = AddPersonToSubGroup(PeopleToAdd)
        self.AddPersonDiag.show()
        self.connect(self.AddPersonDiag, QtCore.SIGNAL("accepted()"), self.AddPeopleSelect)
        
    def AddPeopleSelect(self):
        NewPeople = self.AddPersonDiag.GetAddedPeople()
        for PID in NewPeople:
            self.AddedPIDs.append([PID, 0.0])
        self.PopulateTable()
             
    def InitTable(self):
        PeopleDict = self.Database.People.GetAllPeopleDict()
        if self.SgExp_id != -1:
            Expense = self.Database.SubGroupExpenses.GetSubGroupExpenses(SgExp_id = self.SgExp_id)[0]
            self.CurrentPID = Expense.PID
            self.ExpenseAmount.setText("""$%.2f"""%Expense.Amount)
            self.Amount = self.ExpenseAmount.text()
            Desc = Expense.Desc.split('\n\n')
            self.ExpenseTitle.setText(Desc[0])
            self.ExpenseDesc.setPlainText(Desc[-1])
            date = QtCore.QDate(Expense.Date.year, Expense.Date.month, Expense.Date.day)
            self.ExpenseDate.setDate(date)
        else:
            self.ExpenseAmount.setText("""$%.2f"""%0.0)
            self.Amount = self.ExpenseAmount.text()
            
            self.ExpenseDate.setDate(DefaultDate)
            
            self.ExpenseTitle.setText("")
            self.ExpenseDesc.setPlainText("")
              
    def PopulateTable(self):
        self.disconnect(self.tableWidget, QtCore.SIGNAL("cellChanged(int, int)"), self.UpdateProps)
        PeopleDict = self.Database.People.GetAllPeopleDict()
        Sum = 0.0
        while(self.tableWidget.rowCount() > 0):
            self.tableWidget.removeRow(0)
        for PID, Prop in self.AddedPIDs:
            Person = PeopleDict[PID]
            self.tableWidget.insertRow(self.tableWidget.rowCount())
            #self.tableWidget.setItem(self.tableWidget.rowCount()-1, 0, QtGui.QTableWidgetItem("""%d"""%Person.PID))
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 0, QtGui.QTableWidgetItem("""%s %s"""%(Person.f_Name, Person.l_Name)))
            
            if float(self.ExpenseAmount.text().replace('$','')) > 0:
                Percentage = 100.0*(Prop/float(self.ExpenseAmount.text().replace('$','')))
            else:
                Percentage = 0.0
            
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 1, QtGui.QTableWidgetItem("""%.2f %s"""%(Percentage, "%")))
            #self.connect( self.tableWidget.item(self.tableWidget.rowCount()-1, 2), QtCore.SIGNAL("editingFinished()"), self.UpdateAmount)
            
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 2, QtGui.QTableWidgetItem("""%s %.2f"""%("$", Prop)))
            Sum = Sum + Prop
            
            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 3, QtGui.QPushButton("Delete"))
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 3).uniqueId = """%d"""%Person.PID
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 3).clicked.connect(self.OnDeletePerson)

            i = 0
            while (i < self.tableWidget.columnCount()):
                self.tableWidget.resizeColumnToContents(i)
                i = i + 1
                
        self.tableWidget.insertRow(self.tableWidget.rowCount())
        self.tableWidget.setItem(self.tableWidget.rowCount()-1, 2, QtGui.QTableWidgetItem("""%s %.2f"""%("$", Sum)))
        self.connect(self.tableWidget, QtCore.SIGNAL("cellChanged(int, int)"), self.UpdateProps)
    
    def EvenlyDitributeExpense(self):
        Count = len(self.AddedPIDs)
        Amount = float(self.ExpenseAmount.text().replace('$',''))
        Proportion = int(100.0*round(Amount/Count,2))
        sum = 0
        i = 0
        while i < Count-1:
            self.AddedPIDs[i] = [self.AddedPIDs[i][0], round((1.0*Proportion)/100.0,2)]
            sum = sum + Proportion
            i = i + 1
        Proportion = int(100.0*Amount) - sum
        self.AddedPIDs[i] = [self.AddedPIDs[i][0], round((1.0*Proportion)/100.0,2)]
        self.PopulateTable()
        
    def CheckProps(self):
        Total = 0
        for PID, Prop in self.AddedPIDs:
            Total = int(int(Prop*100.0) + Total)
        return int(Total) - int(100.0*float(self.ExpenseAmount.text().replace('$','')))
    
    def UpdateProps(self, row, col):
        if col == 1:
            Value = (float(self.tableWidget.cellWidget(row, col).text().replace("""%""",''))/100.0)*float(self.ExpenseAmount.text().replace('$',''))
        
        if col == 2:
            Value = float(self.tableWidget.cellWidget(row, col).text().replace('$',''))
            
        ##update Prop
        PPID =  int(self.tableWidget.cellWidget(row, 3).uniqueId)
        for PID, Prop in self.AddedPIDs:
            if PID == PPID:
                item = [PID, Prop]
                
        self.AddedPIDs.remove(item)
        self.AddedPIDs.append([PPID, Value])
            
        self.PopulateTable()
            
    def OnDeletePerson(self):
        PIDToDelete = int(self.sender().uniqueId)
        NewList = []
        for PID, Prop in self.AddedPIDs:
            if PID != PIDToDelete:
                NewList.append([PID, Prop])
            
        self.AddedPIDs = NewList
        self.PopulateTable()

class ViewSubGroupExpense(QtGui.QDialog, Ui_ViewSubGroupExpenseDiag):
    def __init__(self, Database):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.Database = Database
        global EventId
        self.EventId = EventId
        self.PopulateTable()
        
        self.connect(self.AddExpenseButton, QtCore.SIGNAL("clicked()"), self.AddNewExpense)
        
    def PopulateTable(self):
        while(self.tableWidget.rowCount() > 0):
            self.tableWidget.removeRow(0)
        
        Expenses = self.Database.SubGroupExpenses.GetSubGroupExpenses(EID = self.EventId)
        People = self.Database.People.GetAllPeopleDict()
        for Expense in Expenses:
            self.tableWidget.insertRow(self.tableWidget.rowCount())
            #self.tableWidget.setItem(self.tableWidget.rowCount()-1, 0, QtGui.QTableWidgetItem("""%d"""%Expense.SgExp_id))
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 0, QtGui.QTableWidgetItem("""%d/%d/%d"""%(Expense.Date.day, Expense.Date.month, Expense.Date.year)))
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 1, QtGui.QTableWidgetItem("""%s"""%Expense.Desc.split("\n\n")[0]))
            Person = People[Expense.PID]
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 2, QtGui.QTableWidgetItem("""%s %s"""%(Person.f_Name, Person.l_Name)))
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 3, QtGui.QTableWidgetItem("""$%.2f"""%Expense.Amount))
            
            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 4, QtGui.QComboBox())
            PIDsInGroup = self.Database.SubGroupExpenses.GetAllPeopleInSubgroupOnEvent(Expense.SgExp_id, self.EventId)
            for PID, Prop in PIDsInGroup:
                Person = People[PID]
                self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 4).addItem("""%s %s"""%(Person.f_Name, Person.l_Name))

            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 5, QtGui.QPushButton("Edit"))
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 5).uniqueId = """%d"""%Expense.SgExp_id
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 5).clicked.connect(self.OnEditEvent)
            
            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 6, QtGui.QPushButton("Delete"))
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 6).uniqueId = """%d"""%Expense.SgExp_id
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 6).clicked.connect(self.OnDeleteEvent)
      
    def OnEditEvent(self):
        SgExp_id =  int(self.sender().uniqueId)
        self.EditEventDiag = AddSubGroupExpense(self.Database, SgExp_id)
        self.EditEventDiag.show()
        self.connect(self.EditEventDiag, QtCore.SIGNAL("accepted()"), self.EditAccepted)
        
    def EditAccepted(self):
        self.PopulateTable()
    
    def AddNewExpense(self):
        self.AddExpenseDiag = AddSubGroupExpense(self.Database)
        self.AddExpenseDiag.show()
        self.connect(self.AddExpenseDiag, QtCore.SIGNAL("accepted()"), self.AddAccepted)
    
    def AddAccepted(self):
        self.PopulateTable()

    def OnDeleteEvent(self, Exp_Id):
        SgExp_id =  int(self.sender().uniqueId)
        self.ConfirmDelete = ConfirmDiag("Are you sure you want to delete?")
        self.ConfirmDelete.ID = str(SgExp_id)
        self.connect(self.ConfirmDelete, QtCore.SIGNAL("accepted()"), self.DeleteExpenseAccepted)
        self.ConfirmDelete.show()
        
    def DeleteExpenseAccepted(self):
        SgExp_id = int(self.ConfirmDelete.ID)
        self.Database.SubGroupExpenses.RemoveSubGroupExpense(SgExp_id)
        self.PopulateTable()

class ManagePeopleOnEvent(QtGui.QDialog, Ui_AddPersonToEventDiag):
    def __init__(self, Database):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        
        self.Database = Database
        
        self.PIDsInList = []
        PIDSOnEvent = self.Database.Events.GetAllPeopleOnEvent(EventId)
        for PID, Dates in PIDSOnEvent:
            self.PIDsInList.append(PID)
        
        self.PopulateList()
        self.connect(self.AddPeopleButton, QtCore.SIGNAL("clicked()"), self.AddPerson)
        self.connect(self.DoneButton,QtCore.SIGNAL("clicked()"), self.Done)
    
    def PopulateList(self):
        global EventId
        while(self.tableWidget.rowCount() > 0):
            self.tableWidget.removeRow(0)
        People = self.Database.People.GetAllPeopleDict()
        
        
        for PID in self.PIDsInList:
            self.tableWidget.insertRow(self.tableWidget.rowCount())
            Person = People[PID]
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 0, QtGui.QTableWidgetItem("""%s %s"""%(Person.f_Name, Person.l_Name)))
            
            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 1, QtGui.QPushButton("Delete"))
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 1).uniqueId = """%d"""%Person.PID
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 1).clicked.connect(self.OnDeletePerson)
    
    def OnDeletePerson(self):
        PIDToDelete = int(self.sender().uniqueId)
        self.PIDsInList.remove(PIDToDelete)
        self.PopulateList()
    
    def AddPerson(self):
        global EventId
        People = self.Database.People.GetAllPeopleDict()
        PeopleToAdd = []
        for PID in People.keys():
            if PID in self.PIDsInList:
                pass
            else:
                PeopleToAdd.append(People[PID])
                
        self.AddPersonDiag = AddPersonToSubGroup(PeopleToAdd)
        self.AddPersonDiag.show()
        self.connect(self.AddPersonDiag, QtCore.SIGNAL("accepted()"), self.AddPeopleSelect)
            
    def AddPeopleSelect(self):
        NewPeople = self.AddPersonDiag.GetAddedPeople()
        for PID in NewPeople:
            self.PIDsInList.append(PID)
        self.PopulateList()
            
    def Done(self):
        global EventId
        PIDSOnEvent = self.Database.Events.GetAllPeopleOnEvent(EventId)
        for PID, Prop in PIDSOnEvent:
            if PID in self.PIDsInList:
                self.PIDsInList.remove(PID)
            else:
                self.Database.Events.RemovePersonFromEvent(EventId, PID)
        if len(self.PIDsInList)> 0:
            Dates = []
            Delta = 0
            Event = self.Database.Events.GetEvent(EID = EventId)[0]
            StartDate = Event.StartDate
            EndDate = Event.EndDate
            while (StartDate + datetime.timedelta(Delta)) != EndDate:
                Dates.append((StartDate + datetime.timedelta(Delta),100))
                Delta = Delta + 1
            Dates.append((StartDate + datetime.timedelta(Delta),100))
            for PID in self.PIDsInList:
                self.Database.Events.AddPersonToEvent(PID, EventId, Dates)
        self.accept()

class AddPersonToSubGroup(QtGui.QDialog, Ui_AddPersonToSubGroupDiag):
    def __init__(self, People):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.People = People
        self.PopulateTable()
        
    def PopulateTable(self):
        for Person in self.People:
            self.tableWidget.insertRow(self.tableWidget.rowCount())
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 0, QtGui.QTableWidgetItem("""%d"""%Person.PID))
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 1, QtGui.QTableWidgetItem("""%s %s"""%(Person.f_Name, Person.l_Name)))
            
            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 2, QtGui.QCheckBox())
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 2).setTristate(False)
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 2).setCheckState(0)
            i = 0
            while (i < self.tableWidget.columnCount()):
                self.tableWidget.resizeColumnToContents(i)
                i = i + 1
                
    def GetAddedPeople(self):
        PIDS = []
        while self.tableWidget.rowCount() != 0:
            if self.tableWidget.cellWidget(0, 2).checkState() == 2:
                PIDS.append(int(self.tableWidget.item(0,0).text()))
            self.tableWidget.removeRow(0)
        return PIDS

class ViewSpendingSummary(QtGui.QDialog, Ui_ViewSpendingSummaryDiag):
    def __init__(self, Database):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.Database = Database
        global PID
        global EventId
        self.CurrentPID = PID
        self.PopulateComboBox()
        self.PopulateSpendingTable()
    
    def PopulateComboBox(self):
        self.comboBox.clear()
        People = self.Database.GetPeopleOnEvent(EventId)
        index = 0
        for Person in People:
            if Person.PID == self.CurrentPID:
                index = self.comboBox.count()
            self.comboBox.addItem("""%s %s"""%(Person.f_Name, Person.l_Name))
            self.comboBox.setItemData(self.comboBox.count()-1, Person.PID)
        self.comboBox.setCurrentIndex(index)
        self.connect(self.comboBox, QtCore.SIGNAL("currentIndexChanged(int)"), self.ComboChange)
    
    def ComboChange(self):
        self.CurrentPID = self.comboBox.itemData(self.comboBox.currentIndex()).toInt()[0]
        self.PopulateSpendingTable()
    
    def PopulateSpendingTable(self):
        global EventId
        Total = 0.0
        while(self.tableWidget_2.rowCount() > 0):
            self.tableWidget_2.removeRow(0)
        Expenses = self.Database.TripExpenses.GetExpenses(EID=EventId, PID = self.CurrentPID)
        for Expense in Expenses:
            self.tableWidget_2.insertRow(self.tableWidget_2.rowCount())
            self.tableWidget_2.setItem(self.tableWidget_2.rowCount()-1, 0, QtGui.QTableWidgetItem("""%s"""%(Expense.Desc.split('\n\n')[0])))
            self.tableWidget_2.setItem(self.tableWidget_2.rowCount()-1, 1, QtGui.QTableWidgetItem("""$%0.2f"""%(Expense.Amount)))
            Total = Total + Expense.Amount
            self.tableWidget_2.setCellWidget(self.tableWidget_2.rowCount()-1, 2, QtGui.QPushButton("Edit"))
            self.tableWidget_2.cellWidget(self.tableWidget_2.rowCount()-1, 2).uniqueId = """%d"""%Expense.TexID
            self.tableWidget_2.cellWidget(self.tableWidget_2.rowCount()-1, 2).clicked.connect(self.OnEditGroupExpense)
        while(self.tableWidget_3.rowCount() > 0):
            self.tableWidget_3.removeRow(0)
        Expenses = self.Database.SubGroupExpenses.GetSubGroupExpenses(EID=EventId, PID = self.CurrentPID)
        for Expense in Expenses:
            self.tableWidget_3.insertRow(self.tableWidget_3.rowCount())
            self.tableWidget_3.setItem(self.tableWidget_3.rowCount()-1, 0, QtGui.QTableWidgetItem("""%s"""%(Expense.Desc.split('\n\n')[0])))
            self.tableWidget_3.setItem(self.tableWidget_3.rowCount()-1, 1, QtGui.QTableWidgetItem("""$%0.2f"""%(Expense.Amount)))
            Total = Total + Expense.Amount
            self.tableWidget_3.setCellWidget(self.tableWidget_3.rowCount()-1, 2, QtGui.QPushButton("Edit"))
            self.tableWidget_3.cellWidget(self.tableWidget_3.rowCount()-1, 2).uniqueId = """%d"""%Expense.SgExp_id
            self.tableWidget_3.cellWidget(self.tableWidget_3.rowCount()-1, 2).clicked.connect(self.OnEditSubGroupExpense)
        
        
        self.lineEdit_2.setText("""$%0.2f"""%Total)
        
    def OnEditGroupExpense(self):
        TExpId =  int(self.sender().uniqueId)
        self.EditExpenseDiag = EditTripExpense(self.Database, TExpId)
        self.EditExpenseDiag.show()
        self.connect(self.EditExpenseDiag, QtCore.SIGNAL("accepted()"), self.PopulateSpendingTable)
        self.connect(self.EditExpenseDiag, QtCore.SIGNAL("rejected()"), self.PopulateSpendingTable)
        
    def OnEditSubGroupExpense(self):
        SgExpId =  int(self.sender().uniqueId)
        self.EditGroupExpenseDiag = AddSubGroupExpense(self.Database, SgExpId)
        self.EditGroupExpenseDiag.show()
        self.connect(self.EditGroupExpenseDiag, QtCore.SIGNAL("accepted()"), self.PopulateSpendingTable)
        self.connect(self.EditGroupExpenseDiag, QtCore.SIGNAL("rejected()"), self.PopulateSpendingTable)
      
class ViewExpenseSummary(QtGui.QDialog, Ui_ViewExpenseSummaryDiag):
    def __init__(self, Database):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.Database = Database
        global PID
        global EventId
        self.CurrentPID = PID
        self.Editible = True
        
        self.PopulateComboBox()
        self.PopulateGroupExpenses()
        self.connect(self.DoneButton, QtCore.SIGNAL("clicked()"), self.EventDoneButton)
    
    def PopulateComboBox(self):
        self.comboBox.clear()
        People = self.Database.GetPeopleOnEvent(EventId)
        index = 0
        for Person in People:
            if Person.PID == self.CurrentPID:
                index = self.comboBox.count()
            self.comboBox.addItem("""%s %s"""%(Person.f_Name, Person.l_Name))
            self.comboBox.setItemData(self.comboBox.count()-1, Person.PID)
        self.comboBox.setCurrentIndex(index)
        self.connect(self.comboBox, QtCore.SIGNAL("currentIndexChanged(int)"), self.ComboChange)
    
    def ComboChange(self):
        self.UpdateTripExpenseStatus()
        self.CurrentPID = self.comboBox.itemData(self.comboBox.currentIndex()).toInt()[0]
        deps = self.Database.People.GetAllPersonsDeps(PID)
        if self.CurrentPID == PID:
            self.Editible = True
        elif self.CurrentPID in deps:
            self.Editible = True
        else:
            self.Editible = False
        self.PopulateGroupExpenses()
    
    def PopulateGroupExpenses(self):
        global EventId
        Total = 0.0
        while(self.tableWidget_2.rowCount() > 0):
            self.tableWidget_2.removeRow(0)
        Expenses = self.Database.GetTripExpensesOfPerson(EventId, self.CurrentPID)
        Statuses = self.Database.TripExpenses.GetPersonsAccepts(self.CurrentPID, EventId)
        for Expense,Prop in Expenses:
            self.tableWidget_2.insertRow(self.tableWidget_2.rowCount())
            self.tableWidget_2.setItem(self.tableWidget_2.rowCount()-1, 0, QtGui.QTableWidgetItem("""%s"""%(Expense.Desc.split('\n\n')[0])))
            self.tableWidget_2.setItem(self.tableWidget_2.rowCount()-1, 1, QtGui.QTableWidgetItem("""$%0.2f"""%(Expense.Amount)))
            self.tableWidget_2.setItem(self.tableWidget_2.rowCount()-1, 2, QtGui.QTableWidgetItem("""$%0.2f"""%(Prop*Expense.Amount)))
            self.tableWidget_2.setCellWidget(self.tableWidget_2.rowCount()-1, 3, QtGui.QCheckBox())
            self.tableWidget_2.cellWidget(self.tableWidget_2.rowCount()-1, 3).setTristate(False)
            self.tableWidget_2.cellWidget(self.tableWidget_2.rowCount()-1, 3).uniqueId = """%d"""%Expense.TexID
            if Expense.TexID in Statuses.keys():
                State = int(Statuses[Expense.TexID])
            else:
                State = 0
            self.tableWidget_2.cellWidget(self.tableWidget_2.rowCount()-1, 3).setCheckState(State)
            self.tableWidget_2.cellWidget(self.tableWidget_2.rowCount()-1, 3).setEnabled(self.Editible)
            Total = Total + Prop * Expense.Amount
            
            
        while(self.tableWidget_3.rowCount() > 0):
            self.tableWidget_3.removeRow(0)
        Expenses = self.Database.SubGroupExpenses.GetSubgroupExpensesOfPerson(self.CurrentPID, EventId)
        Statuses = self.Database.SubGroupExpenses.GetAcceptState(self.CurrentPID, EventId)
        for Expense,Prop in Expenses:
            self.tableWidget_3.insertRow(self.tableWidget_3.rowCount())
            self.tableWidget_3.setItem(self.tableWidget_3.rowCount()-1, 0, QtGui.QTableWidgetItem("""%s"""%(Expense.Desc.split('\n\n')[0])))
            self.tableWidget_3.setItem(self.tableWidget_3.rowCount()-1, 1, QtGui.QTableWidgetItem("""$%0.2f"""%(Expense.Amount)))
            self.tableWidget_3.setItem(self.tableWidget_3.rowCount()-1, 2, QtGui.QTableWidgetItem("""$%0.2f"""%(Prop)))
            Total = Total + Prop 
            self.tableWidget_3.setCellWidget(self.tableWidget_3.rowCount()-1, 3, QtGui.QPushButton("Edit"))
            self.tableWidget_3.cellWidget(self.tableWidget_3.rowCount()-1, 3).uniqueId = """%d"""%Expense.SgExp_id
            self.tableWidget_3.cellWidget(self.tableWidget_3.rowCount()-1, 3).clicked.connect(self.OnEditEvent)
            
            self.tableWidget_3.setCellWidget(self.tableWidget_3.rowCount()-1, 4, QtGui.QCheckBox())
            self.tableWidget_3.cellWidget(self.tableWidget_3.rowCount()-1, 4).setTristate(False)
            self.tableWidget_3.cellWidget(self.tableWidget_3.rowCount()-1, 4).uniqueId = """%d"""%Expense.SgExp_id
            if Expense.SgExp_id in Statuses.keys():
                State = int(Statuses[Expense.SgExp_id])
            else:
                State = 0
            self.tableWidget_3.cellWidget(self.tableWidget_3.rowCount()-1, 4).setCheckState(State)
            self.tableWidget_3.cellWidget(self.tableWidget_3.rowCount()-1, 4).setEnabled(self.Editible)
            
            
            
        self.lineEdit_2.setText("""$%0.2f"""%Total)
            
    def OnEditEvent(self):
        SGExpId =  int(self.sender().uniqueId)
        self.EditExpenseDiag = AddSubGroupExpense(self.Database, SGExpId)
        self.EditExpenseDiag.show()
        self.connect(self.EditExpenseDiag, QtCore.SIGNAL("accepted()"), self.PopulateGroupExpenses)
        self.connect(self.EditExpenseDiag, QtCore.SIGNAL("rejected()"), self.PopulateGroupExpenses)
        
    def EventDoneButton(self):
        print "Finished"
        self.UpdateTripExpenseStatus()
        self.accept()
        
    def UpdateTripExpenseStatus(self):
        if self.Editible:
            i = 0
            Statuses = self.Database.TripExpenses.GetPersonsAccepts(self.CurrentPID, EventId)
            while i < self.tableWidget_2.rowCount():
                TExp = int(self.tableWidget_2.cellWidget(i, 3).uniqueId)
                if TExp in  Statuses.keys():
                    self.Database.TripExpenses.UpdateEventPeople(EventId, self.CurrentPID, TExp,
                                                                      int(self.tableWidget_2.cellWidget(i, 3).checkState()))
                else:
                    self.Database.TripExpenses.AddPersonExpenseStatus(self.CurrentPID, EventId,
                                                                      TExp, int(self.tableWidget_2.cellWidget(i, 3).checkState()))
                i = i + 1
            i = 0
            Statuses = self.Database.SubGroupExpenses.GetAcceptState(self.CurrentPID, EventId)
            while i < self.tableWidget_3.rowCount():
                SGExp = int(self.tableWidget_3.cellWidget(i, 4).uniqueId)
                if SGExp in Statuses.keys():
                    self.Database.SubGroupExpenses.SetAcceptState(self.CurrentPID, SGExp,
                                                                  int(self.tableWidget_3.cellWidget(i, 4).checkState()))
                i = i + 1
      
class TripExpensesMainWindow(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)    
        self.setupUi(self)
        
        global DefaultDate
        DefaultDate = QtCore.QDate.currentDate()
        
        self.Database = Database.Database()
        
        self.SignInStart()
        self.Timer = QtCore.QTimer()
        self.GetDataThread = GetMainDataThread(self.Database, "", args = ())
        
    def Exit(self):
        self.close()
    
    def InitActions(self):
        self.connect(self.actionView_Trip_Expenses,QtCore.SIGNAL("triggered()"), self.ActionViewTripExpenses)
        self.connect(self.actionView_Subgroup_Expenses, QtCore.SIGNAL("triggered()"), self.ActionViewSubgroupExpense)

        self.connect(self.actionManage_People_On_Event, QtCore.SIGNAL("triggered()"), self.ActionManagePeopleOnEvent)
        self.connect(self.actionEdit_People, QtCore.SIGNAL("triggered()"), self.ActionEditPeople)
        self.connect(self.actionManage_Dependants, QtCore.SIGNAL("triggered()"), self.ActionManageDependants)
        self.connect(self.actionEmail_People_On_Event, QtCore.SIGNAL("triggered()"), self.ActionEmailEvent)

        self.connect(self.actionView_Spending_Summary, QtCore.SIGNAL("triggered()"), self.ActionViewSpendingSummary)
        self.connect(self.actionView_Expense_Summary, QtCore.SIGNAL("triggered()"), self.ActionViewExpenseSummary)
        
        self.connect(self.actionModify_Details, QtCore.SIGNAL("triggered()"), self.ActionModifyPersonalDetails)
        self.connect(self.actionEdit_Dates_On_Event,QtCore.SIGNAL("triggered()"), self.ActionEditDateOnEvent)
        
        self.connect(self.actionMake_Payment, QtCore.SIGNAL("triggered()"), self.ActionMake_Payment)
        self.connect(self.actionView_Payments, QtCore.SIGNAL("triggered()"), self.ActionViewPayments)

        
        self.connect(self.actionGenerate_Payment_Matrix_2, QtCore.SIGNAL("triggered()"), self.GenerateMatrix)
        
        if Admin:
            self.menuAdmin_2.setTitle(QtGui.QApplication.translate("MainWindow", "Admin", None, QtGui.QApplication.UnicodeUTF8))
            
        else:
            self.menuAdmin_2.setTitle(QtGui.QApplication.translate("MainWindow", "", None, QtGui.QApplication.UnicodeUTF8))
        self.StartUpdateMainWindowProcess()
        
       
        self.Timer.setInterval(30000) 
        self.Timer.setSingleShot(True)
        QtCore.QObject.connect(self.Timer, QtCore.SIGNAL("timeout()"), self.StartUpdateMainWindowProcess)
        self.Timer.start()
        
    
    def SignInStart(self):
        self.SigninDiag = SignIn()
        self.SigninDiag.show()
        self.connect(self.SigninDiag, QtCore.SIGNAL("accepted()"), self.SignInNameEntered)
        self.connect(self.SigninDiag, QtCore.SIGNAL("rejected()"), self.Exit)
    
    def SignInNameEntered(self):
        global Admin
        global PID
        UsrName = self.SigninDiag.NameEdit.text()
        Password = self.SigninDiag.Password.text()
        #print Password
        if UsrName == '':
            self.SignInStart()
        else:
            Person = self.Database.People.GetPerson(UserName = UsrName)
            if len(Person) > 0:
                Person = Person[0]
                if Person.CheckPassword(Password):
                    PID = Person.PID
                    Admin = Person.Admin
                    self.SignInSelectEvent()
                else:
                    self.ErrorBox = QtGui.QMessageBox(self)
                    self.ErrorBox.setText("Sorry that password was incorrect")
                    self.SignInStart()
                    self.ErrorBox.show()

            else:
                self.ErrorBox = QtGui.QMessageBox(self)
                self.ErrorBox.setText("Sorry that username was incorrect")
                self.SignInStart()
                self.ErrorBox.show()
                
                
                
                
    
    def SignInSelectEvent(self):
        if Admin:
            self.SelectEventDiag = SelectEventAdmin(self.Database)
        else:
            self.SelectEventDiag = SelectEvent(self.Database)
        self.SelectEventDiag.show()
        
        self.connect(self.SelectEventDiag, QtCore.SIGNAL("accepted()"), self.SignInEventEntered)
        self.connect(self.SelectEventDiag, QtCore.SIGNAL("rejected()"), self.Exit)
        
    def SignInEventEntered(self):
        global EventId
        EventId = self.SelectEventDiag.GetEvent()
        Event = self.Database.Events.GetEvent(EID = EventId)[0]
        self.EventNameDisp.setText(Event.EventName)
        self.InitActions()
        
    def ActionViewTripExpenses(self):
        self.VeiwTripExpensesDiag = ViewTripExpense(self.Database)
        self.VeiwTripExpensesDiag.show()
    
    def ActionViewSubgroupExpense(self):
        self.ViewSubGroupExpenseDiag = ViewSubGroupExpense(self.Database)
        self.ViewSubGroupExpenseDiag.show()

    def ActionViewSpendingSummary(self):
        self.ViewSpendingSummaryDiag = ViewSpendingSummary(self.Database)
        self.ViewSpendingSummaryDiag.show()

    def ActionViewExpenseSummary(self):
        self.ViewExpenseSummaryDiag = ViewExpenseSummary(self.Database)
        self.ViewExpenseSummaryDiag.show()

    def ActionManagePeopleOnEvent(self):
        self.ManagePeopleOnEventDiag = ManagePeopleOnEvent(self.Database)
        self.ManagePeopleOnEventDiag.show()
        self.connect(self.ManagePeopleOnEventDiag, QtCore.SIGNAL("accepted()"), self.StartUpdateMainWindowProcess)
        
    def ActionManageDependants(self):
        self.DependantsDiag =  Dedendants(self.Database)
        self.DependantsDiag.show()
        
    def ActionModifyPersonalDetails(self):
        self.UserDetailsDiag = ModifyDetails(self.Database)
        self.UserDetailsDiag.show()
        
    def ActionEditDateOnEvent(self):
        self.EditDatesOnEventDiag = DatesOnEventDiag(self.Database)
        self.EditDatesOnEventDiag.show()
    
    def ActionEditPeople(self):
        self.EditPeopleDiag = EditPeople(self.Database)
        self.EditPeopleDiag.show()
        
    def ActionEmailEvent(self):
        self.EmailPeopleOnEventDiag = EmailPeopleOnEvent(self.Database)
        self.EmailPeopleOnEventDiag.show()
    def ActionMake_Payment(self):
        self.MakePaymentDiag = MakePayment(self.Database)
        self.MakePaymentDiag.show()
        
    def ActionViewPayments(self):
        self.ViewPaymentDiag = ViewPayments(self.Database)
        self.ViewPaymentDiag.show()
        
    def GenerateMatrix(self):
        self.PaymentMatrixDiag = PaymentMatrixDiag(self.Database)
        self.PaymentMatrixDiag.show()
        
    def StartUpdateMainWindowProcess(self):
        self.Timer.stop()
        if self.GetDataThread.isRunning():
            pass
        else:
            self.GetDataThread = GetMainDataThread(self.Database, self.Database.GetOverallSummary, args = (EventId))
            self.connect(self.GetDataThread, QtCore.SIGNAL("update(PyQt_PyObject)"), self.PopulateMainWindowSpreadDataRec)
            self.GetDataThread.start()
            #Data = self.Database.GetOverallSummary(EventId)
            #self.PopulateMainWindowSpreadDataRec(Data)
        self.Timer.setInterval(30000)
        self.Timer.start()
    
    def PopulateMainWindowSpreadDataRec(self, Data):
        while(self.MainPagetable.rowCount() > 0):
            self.MainPagetable.removeRow(0)
        for Line in Data:
            self.MainPagetable.insertRow(self.MainPagetable.rowCount())
            i = 0
            Status = Line[-1]
            while i < len(Line)-1:
                Item = QtGui.QTableWidgetItem("""%s"""%Line[i])
                if Status:
                    Item.setBackgroundColor(QtGui.QColor(59,255,5))
                else:
                    Item.setBackgroundColor(QtGui.QColor(255,255,255))
                    
                self.MainPagetable.setItem(self.MainPagetable.rowCount()-1, i, Item)
                i = i + 1
        i = 0
        while (i < self.MainPagetable.columnCount()):
            self.MainPagetable.resizeColumnToContents(i)
            i = i + 1
        
class GetMainDataThread(QtCore.QThread):
    def __init__(self, Database, Function, args = ()):
        QtCore.QThread.__init__(self)
        self.Database = Database
        self.args = args
        self.Function = Function
        
        
    def run(self):
        Data = self.Function(self.args)
        self.emit( QtCore.SIGNAL('update(PyQt_PyObject)'), Data)
        return
        
app = QtGui.QApplication(sys.argv)
form = TripExpensesMainWindow()
form.show()
app.exec_()